package com.topscore.uke.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.topscore.uke.R;
import com.topscore.uke.entities.MemberEntity;
import com.topscore.uke.mvp.contractors.GetMemberListContractor;
import com.topscore.uke.mvp.presenters.GetMemberListPresenter;
import com.topscore.uke.ui.ToolBarCompatActivity;
import com.topscore.uke.ui.fragments.MemberListSearchResultFragment;
import com.topscore.uke.ui.loadsir_callback.EmptyCallBack;
import com.topscore.uke.ui.loadsir_callback.ErrorCallBack;
import com.topscore.uke.ui.loadsir_callback.LoadingCallBack;
import com.topscore.uke.utils.DisplayImageOptionsManager;
import com.topscore.uke.utils.SnackBarUtil;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.yokeyword.indexablerv.IndexableAdapter;
import me.yokeyword.indexablerv.IndexableLayout;

public class MyMembersListActivity extends ToolBarCompatActivity implements GetMemberListContractor.View {

    @Bind(R.id.list_recycler)
    IndexableLayout listRecycler;
    @Bind(R.id.search_edt)
    EditText searchEdt;
    @Bind(R.id.search_result_container)
    FrameLayout searchResultContainer;
    @Bind(R.id.clear_btn)
    ImageView clearBtn;

    private RecyclerAdapter mAdapter;

    private List<MemberEntity> mMemberList;

    private GetMemberListContractor.Presenter mGetMemberListPresenter;

    private MemberListSearchResultFragment mSearchResultFragment;
    private FragmentManager mFragmentManager;

    private LoadService mLoadService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_members_list);
        ButterKnife.bind(this);
        initViews();
    }

    private void initViews() {
        setCentralTitle("我的会员");
        mLoadService = LoadSir.getDefault().register(listRecycler, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {

            }
        });
        listRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mAdapter = new RecyclerAdapter();
        listRecycler.setAdapter(mAdapter);
        searchEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s != null && s.length() > 0) {
                    searchMember(s.toString());
                    clearBtn.setVisibility(View.VISIBLE);
                } else {
                    clearBtn.setVisibility(View.GONE);
                    FragmentTransaction transaction = mFragmentManager.beginTransaction();
                    transaction.hide(mSearchResultFragment).commit();
                }
            }
        });
        clearBtn.setOnClickListener(view -> {
            searchEdt.setText("");
        });
        initSearchResultFragment();
        initData();
    }

    private void initSearchResultFragment() {
        mSearchResultFragment = new MemberListSearchResultFragment();
        mFragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        transaction.add(searchResultContainer.getId(), mSearchResultFragment).hide(mSearchResultFragment).commit();
    }

    private void initData() {
        mGetMemberListPresenter = new GetMemberListPresenter(this);
        mGetMemberListPresenter.getMemberList();
    }

    private void searchMember(String searchWord) {
        mSearchResultFragment.searchMember(searchWord);
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        transaction.show(mSearchResultFragment).commit();
    }

    @Override
    public void onLoading(String loadingMessage) {
//        showLoadingDialog(loadingMessage);
        mLoadService.showCallback(LoadingCallBack.class);
    }

    @Override
    public void onLoadFinished() {
//        dismissLoadingDialog();
        mLoadService.showSuccess();
    }

    @Override
    public void onFail(int code, String errorMessage) {
        mLoadService.showCallback(ErrorCallBack.class);
        SnackBarUtil.getInstance(listRecycler)
                .showLong(errorMessage)
                .setAction("重新加载", v -> initData())
                .show();
    }

    @Override
    public void onGetMemberListSuccess(List<MemberEntity> memberList) {
        if (memberList != null && memberList.size() > 0) {
            mMemberList = memberList;
            mSearchResultFragment.setMemberList(mMemberList);
            mAdapter.setDatas(mMemberList);
        } else {
            mLoadService.showCallback(EmptyCallBack.class);
        }
    }

    private class RecyclerAdapter extends IndexableAdapter<MemberEntity> {

        private LayoutInflater mInflater;

        public RecyclerAdapter() {
            mInflater = getLayoutInflater();

        }

        @Override
        public RecyclerView.ViewHolder onCreateTitleViewHolder(ViewGroup parent) {
            View view = mInflater.inflate(R.layout.member_list_sticky, parent, false);
            return new IndexViewHolder(view);
        }

        @Override
        public RecyclerView.ViewHolder onCreateContentViewHolder(ViewGroup parent) {
            View view = mInflater.inflate(R.layout.member_list_item, parent, false);
            return new ContentViewHolder(view);
        }

        @Override
        public void onBindTitleViewHolder(RecyclerView.ViewHolder holder, String indexTitle) {
            IndexViewHolder indexViewHolder = (IndexViewHolder) holder;
            indexViewHolder.indexTv.setText(indexTitle);
        }

        @Override
        public void onBindContentViewHolder(RecyclerView.ViewHolder holder, MemberEntity entity) {
            ContentViewHolder viewHolder = (ContentViewHolder) holder;
            ImageLoader.getInstance().displayImage(entity.getPortrait(), viewHolder.avatarIv,
                    DisplayImageOptionsManager.getInstance().getAvatarOptions());
            viewHolder.nameTv.setText(entity.getMemberName());
            viewHolder.phoneTv.setText(entity.getPhone());
            viewHolder.addressCountTv.setText(entity.getAddressCount() + "个收货地址");
            viewHolder.convertView.setOnClickListener(v -> {
                Intent intent = new Intent(MyMembersListActivity.this, MemberBasicInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("memberName", entity.getMemberName());
                bundle.putString("memberID", entity.getMemberID());
                bundle.putString("phone", entity.getPhone());
                intent.putExtras(bundle);
                startActivity(intent);
            });
        }

        private class IndexViewHolder extends RecyclerView.ViewHolder {

            private TextView indexTv;

            public IndexViewHolder(View itemView) {
                super(itemView);
                indexTv = (TextView) itemView.findViewById(R.id.tv_index);
            }
        }

        private class ContentViewHolder extends RecyclerView.ViewHolder {
            private TextView nameTv, phoneTv, addressCountTv;
            private ImageView avatarIv;
            private View convertView;

            public ContentViewHolder(View itemView) {
                super(itemView);
                nameTv = (TextView) itemView.findViewById(R.id.name_tv);
                phoneTv = (TextView) itemView.findViewById(R.id.phone_tv);
                avatarIv = (ImageView) itemView.findViewById(R.id.avatar_iv);
                convertView = itemView.findViewById(R.id.item_convert);
                addressCountTv = (TextView) itemView.findViewById(R.id.address_count_tv);
            }
        }
    }
}
